import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:k3cloud_api/params/request_param.dart';

/// it is used to build parameters to request the query interface.
class QueryParam extends RequestParam {
  @override
  String getRequestPath() {
    return "DynamicFormService.ExecuteBillQuery";
  }

  @override
  Map<String, dynamic> parseResponse(String response) {
    List<dynamic> resp = jsonDecode(response);
    // 如果请求失败
    if (resp.length == 1) {
      try {
        Map<String, dynamic> status = resp[0][0]["Result"]["ResponseStatus"];
        return {"data": status};
      } catch (e) {
        debugPrint(e.toString());
      }
    }
    // 请求成功时进入如下解析
    List<String> fields = [];
    if (fieldKeys != null) {
      fields = fieldKeys!.split(",");
    }
    List<dynamic> data = [];
    for (var i = 0; i < resp.length; i++) {
      Map<String, dynamic> item = {};
      for (var j = 0; j < fields.length; j++) {
        item[fields[j]] = resp[i][j];
      }
      data.add(item);
    }
    return {"data": data};
  }

  @override
  Map<String, dynamic> toJson() {
    Map<String, dynamic> data = {};
    if (formId != null) data["formId"] = formId;
    if (fieldKeys != null) data["fieldKeys"] = fieldKeys;
    if (filterString != null) data["filterString"] = filterString;
    if (orderString != null) data["orderString"] = orderString;
    if (topRowCount != null) data["topRowCount"] = topRowCount;
    if (startRow != null) data["startRow"] = startRow;
    if (limit != null) data["limit"] = limit;

    Map<String, dynamic> json = {};
    json["data"] = data;
    return json;
  }

  String? formId;
  String? fieldKeys;
  String? filterString;
  String? orderString;
  int? topRowCount;
  int? startRow;
  int? limit;

  static _Builder builder() {
    return _Builder();
  }
}

class _Builder {
  final QueryParam _param = QueryParam();

  QueryParam build() => _param;
  
  _Builder formId(String formId) {
    _param.formId = formId;
    return this;
  }

  _Builder fieldKeys(List<String> fieldKeys) {
    _param.fieldKeys = fieldKeys.join(",");
    return this;
  }

  _Builder filterString(String filterString) {
    _param.filterString = filterString;
    return this;
  }

  _Builder orderString(String orderString) {
    _param.orderString = orderString;
    return this;
  }

  _Builder topRowCount(int topRowCount) {
    _param.topRowCount = topRowCount;
    return this;
  }

  _Builder startRow(int startRow) {
    _param.startRow = startRow;
    return this;
  }

  _Builder limit(int limit) {
    _param.limit = limit;
    return this;
  }
}